package com.huawei.spare.part.replace.views.widgets.cell;

import com.google.common.base.Strings;
import io.reactivex.rxjavafx.observables.JavaFxObservable;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Font;
import javafx.util.Callback;
import javafx.util.StringConverter;
import javafx.util.converter.DefaultStringConverter;
import org.controlsfx.control.PopOver;

import java.util.concurrent.TimeUnit;

public class TooltipTextFieldTableCell<S, T> extends TextFieldTableCell<S, T> {

    public static <S> Callback<TableColumn<S, String>, TableCell<S, String>> forTableColumn() {
        return forTableColumn(new DefaultStringConverter());
    }

    public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> forTableColumn(
            final StringConverter<T> converter) {
        return list -> new TooltipTextFieldTableCell<S, T>(converter);
    }


    public TooltipTextFieldTableCell(StringConverter<T> converter) {
        super(converter);
    }

    PopOver popOver;

    @Override
    public void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        final StringConverter<T> converter = this.converterProperty().get();
        final String tooltip = converter == null ?
                item == null ? "" : item.toString() : converter.toString(item);
        if (!Strings.isNullOrEmpty(tooltip) && tooltip.length() > 20) {
            final Label label = new Label(tooltip);
            label.setFont(Font.font(14));
            label.setPadding(new Insets(8));
            popOver = new PopOver(label);
            popOver.setArrowLocation(PopOver.ArrowLocation.TOP_LEFT);
            popOver.setArrowSize(3);
            popOver.setArrowIndent(6);
            JavaFxObservable.eventsOf(this, MouseEvent.MOUSE_ENTERED)
                    .delay(400, TimeUnit.MILLISECONDS)
                    .observeOn(JavaFxScheduler.platform())
                    .subscribe(e -> popOver.show(this));
            this.setOnMouseExited(mouseEvent -> popOver.hide());
        } else {
            popOver = null;
        }

//        if (!Strings.isNullOrEmpty(tooltip)) {
//            setTooltip(new Tooltip(tooltip));
//            this.setOnMouseEntered(e -> {
//                if (this.getTooltip() != null) {
//                    FxUtils.showTooltip(this, this.getTooltip());
//                }
//            });
//            this.setOnMouseExited(e-> {
//                if (this.getTooltip() != null) {
//                    this.getTooltip().hide();
//                }
//            });
//        } else {
//            this.setTooltip(null);
//        }
    }


}
